﻿using AutoMapper;
using ERPSystem.Common.Domains.Department;
using ERPSystem.Common.DTO;
using ERPSystem.Common.Infrastructure.IRepository;
using ERPSystem.Enum.CommonErrorCodes;
using MediatR;

namespace BasicInformationWrite.API.BasicInformationCommons.Departes
{
    public class DepartCreateHandler : IRequestHandler<DepartCreateCommand, Result>
    {
        private readonly IBaseRepository<Depart> _departRepository;
        private readonly IMapper _mapper;

        public DepartCreateHandler(IBaseRepository<Depart> departRepository, IMapper mapper)
        {
            _departRepository = departRepository;
            _mapper = mapper;
        }
        /// <summary>
        /// 部门添加业务逻辑
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(DepartCreateCommand request, CancellationToken cancellationToken)
        {
            var result = new Result();
            try
            {
                Depart depart = _mapper.Map<Depart>(request);
                depart.CreatedOwnerId = "张三";
                depart.CreatedTime = DateTime.Now;
                var res = await _departRepository.Add(depart);
                if (res > 0)
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Msg = "添加成功";
                }
                else
                {
                    result.Msg = "添加失败";
                }
            }
            catch (Exception)
            {

                throw;
            }
            return result;
        }
    }
}
